<!-- pages/coupon/create.vue -->
<template>
  <view class="page-container">
    <scroll-view scroll-y class="form-container">
      <!-- 表单内容 -->
      <view class="form-section">
        <!-- 优惠券名称 -->
        <view class="form-item">
          <text class="label required">优惠券名称</text>
          <input 
            v-model="form.name"
            placeholder="请输入优惠券名称"
            class="input"
            :class="{ error: errors.name }"
          />
          <text v-if="errors.name" class="error-tip">{{ errors.name }}</text>
        </view>

        <!-- 优惠券类型 -->
        <view class="form-item">
          <text class="label required">优惠券类型</text>
          <view class="radio-group">
            <label 
              v-for="item in couponTypes" 
              :key="item.value"
              class="radio-item"
              :class="{ active: form.type === item.value }"
            >
              <radio 
                :value="item.value"
                :checked="form.type === item.value"
                @click="form.type = item.value"
                color="#1890ff"
                class="radio"
              />
              <text class="radio-label">{{ item.label }}</text>
            </label>
          </view>
        </view>

        <!-- 满减金额 -->
        <view v-if="form.type === 'FULL_REDUCE'" class="form-item">
          <text class="label required">满减条件</text>
          <view class="inline-inputs">
            <input
              v-model="form.conditionAmount"
              type="number"
              placeholder="满多少元"
              class="input short"
              :class="{ error: errors.conditionAmount }"
            />
            <text class="unit">元减</text>
            <input
              v-model="form.reduceAmount"
              type="number"
              placeholder="减多少元"
              class="input short"
              :class="{ error: errors.reduceAmount }"
            />
            <text class="unit">元</text>
          </view>
          <text v-if="errors.conditionAmount" class="error-tip">{{ errors.conditionAmount }}</text>
          <text v-if="errors.reduceAmount" class="error-tip">{{ errors.reduceAmount }}</text>
        </view>

        <!-- 折扣比例 -->
        <view v-if="form.type === 'DISCOUNT'" class="form-item">
          <text class="label required">折扣比例</text>
          <view class="inline-inputs">
            <input
              v-model="form.discount"
              type="number"
              placeholder="请输入折扣"
              class="input short"
              :class="{ error: errors.discount }"
            />
            <text class="unit">折</text>
          </view>
          <text v-if="errors.discount" class="error-tip">{{ errors.discount }}</text>
        </view>

        <!-- 发放时间 -->
        <view class="form-item">
          <text class="label required">发放时间</text>
          <view class="time-range">
            <picker 
              mode="date" 
              :value="form.issueStart"
              @change="val => form.issueStart = val.detail.value"
            >
              <view class="time-picker" :class="{ error: errors.issueStart }">
                {{ form.issueStart || '开始时间' }}
              </view>
            </picker>
            <text class="separator">至</text>
            <picker 
              mode="date" 
              :value="form.issueEnd"
              @change="val => form.issueEnd = val.detail.value"
            >
              <view class="time-picker" :class="{ error: errors.issueEnd }">
                {{ form.issueEnd || '结束时间' }}
              </view>
            </picker>
          </view>
          <text v-if="errors.issueTime" class="error-tip">{{ errors.issueTime }}</text>
        </view>

        <!-- 使用有效期 -->
        <view class="form-item">
          <text class="label required">使用有效期</text>
          <view class="time-range">
            <picker 
              mode="date" 
              :value="form.validStart"
              @change="val => form.validStart = val.detail.value"
            >
              <view class="time-picker" :class="{ error: errors.validStart }">
                {{ form.validStart || '开始时间' }}
              </view>
            </picker>
            <text class="separator">至</text>
            <picker 
              mode="date" 
              :value="form.validEnd"
              @change="val => form.validEnd = val.detail.value"
            >
              <view class="time-picker" :class="{ error: errors.validEnd }">
                {{ form.validEnd || '结束时间' }}
              </view>
            </picker>
          </view>
          <text v-if="errors.validTime" class="error-tip">{{ errors.validTime }}</text>
        </view>

        <!-- 投放数量 -->
        <view class="form-item">
          <text class="label required">投放数量</text>
          <input 
            v-model="form.total"
            type="number"
            placeholder="请输入投放总数"
            class="input"
            :class="{ error: errors.total }"
          />
          <text v-if="errors.total" class="error-tip">{{ errors.total }}</text>
        </view>

        <!-- 每人限领 -->
        <view class="form-item">
          <text class="label required">每人限领</text>
          <input 
            v-model="form.limit"
            type="number"
            placeholder="请输入每人限领数量"
            class="input"
            :class="{ error: errors.limit }"
          />
          <text v-if="errors.limit" class="error-tip">{{ errors.limit }}</text>
        </view>
      </view>

      <!-- 提交按钮 -->
      <button 
        class="submit-btn"
        :disabled="submitting"
        @click="handleSubmit"
      >
        {{ submitting ? '提交中...' : '确认投放' }}
      </button>
    </scroll-view>
  </view>
</template>

<script setup>
import { reactive, ref } from 'vue'

// 表单数据结构
const form = reactive({
  name: '',
  type: 'FULL_REDUCE',
  conditionAmount: '',
  reduceAmount: '',
  discount: '',
  issueStart: '',
  issueEnd: '',
  validStart: '',
  validEnd: '',
  total: '',
  limit: 1
})

// 验证错误信息
const errors = reactive({
  name: '',
  type: '',
  conditionAmount: '',
  reduceAmount: '',
  discount: '',
  issueTime: '',
  validTime: '',
  total: '',
  limit: ''
})

// 页面状态
const submitting = ref(false)
const couponTypes = ref([
  { label: '满减券', value: 'FULL_REDUCE' },
  { label: '折扣券', value: 'DISCOUNT' }
])

// 表单验证规则
const validateForm = () => {
  let isValid = true
  const resetErrors = () => Object.keys(errors).forEach(key => errors[key] = '')

  resetErrors()

  // 通用验证方法
  const addError = (field, message) => {
    errors[field] = message
    isValid = false
  }

  // 名称验证
  if (!form.name.trim()) {
    addError('name', '优惠券名称不能为空')
  }

  // 类型相关验证
  if (form.type === 'FULL_REDUCE') {
    if (!form.conditionAmount || form.conditionAmount <= 0) {
      addError('conditionAmount', '请输入有效满减金额')
    }
    if (!form.reduceAmount || form.reduceAmount <= 0) {
      addError('reduceAmount', '请输入有效减免金额')
    }
  } else if (form.type === 'DISCOUNT') {
    if (!form.discount || form.discount < 1 || form.discount > 9.9) {
      addError('discount', '折扣需在1-9.9之间')
    }
  }

  // 发放时间验证
  if (!form.issueStart || !form.issueEnd) {
    addError('issueTime', '请选择完整发放时间')
  } else if (new Date(form.issueStart) > new Date(form.issueEnd)) {
    addError('issueTime', '发放结束时间不能早于开始时间')
  }

  // 有效期验证
  if (!form.validStart || !form.validEnd) {
    addError('validTime', '请选择完整有效期')
  } else if (new Date(form.validStart) > new Date(form.validEnd)) {
    addError('validTime', '有效期结束不能早于开始')
  }

  // 数量验证
  if (!form.total || form.total < 1) {
    addError('total', '投放数量至少为1')
  }

  // 限领数量验证
  if (!form.limit || form.limit < 1) {
    addError('limit', '限领数量至少为1')
  }

  return isValid
}

// 提交处理
const handleSubmit = async () => {
  if (submitting.value) return
  
  if (!validateForm()) return

  submitting.value = true
  
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 成功后返回并刷新列表
    uni.$emit('coupon-created')
    uni.showToast({ title: '创建成功' })
    setTimeout(() => uni.navigateBack(), 1500)
  } catch (error) {
    uni.showToast({ title: '提交失败，请重试', icon: 'none' })
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  background: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  padding: 32rpx;
}

.form-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.form-item {
  margin-bottom: 48rpx;
  position: relative;

  .label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;

    &.required::after {
      content: '*';
      color: #f5222d;
      margin-left: 8rpx;
    }
  }

  .input {
    height: 88rpx;
    padding: 0 24rpx;
    background: #f8f9fa;
    border-radius: 8rpx;
    font-size: 28rpx;

    &.short {
      width: 200rpx;
      margin-right: 16rpx;
    }

    &.error {
      border: 1rpx solid #f5222d;
    }
  }

  .inline-inputs {
    display: flex;
    align-items: center;

    .unit {
      margin: 0 16rpx;
      color: #666;
    }
  }

  .error-tip {
    position: absolute;
    bottom: -32rpx;
    left: 0;
    color: #f5222d;
    font-size: 24rpx;
  }
}

.radio-group {
  display: flex;
  gap: 32rpx;

  .radio-item {
    display: flex;
    align-items: center;
    padding: 16rpx 32rpx;
    border-radius: 8rpx;
    border: 1rpx solid #ddd;
    transition: all 0.3s;

    &.active {
      border-color: #1890ff;
      background: #e6f7ff;
    }

    .radio {
      transform: scale(0.8);
    }

    .radio-label {
      font-size: 28rpx;
      color: #666;
    }
  }
}

.time-range {
  display: flex;
  align-items: center;
  gap: 16rpx;

  .time-picker {
    flex: 1;
    height: 88rpx;
    line-height: 88rpx;
    padding: 0 24rpx;
    background: #f8f9fa;
    border-radius: 8rpx;
    color: #666;

    &.error {
      border: 1rpx solid #f5222d;
    }
  }

  .separator {
    color: #666;
  }
}

.submit-btn {
  margin-top: 64rpx;
  height: 96rpx;
  line-height: 96rpx;
  background: #1890ff;
  color: #fff;
  border-radius: 48rpx;
  font-size: 32rpx;

  &[disabled] {
    opacity: 0.6;
  }
}
</style>